package com.ldc.model.base;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ldc.common.state.StateCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.util.HashMap;
import java.util.Map;

/**
 * 功能说明
 *
 * @auther liudc
 * @since 2023/6/11
 */
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class ApiBean<T> {
    private T data;
    private int errorCode;
    private String errorMsg;


    public static <T> ApiBean<String> failed() {
        return failed("");
    }

    public static <T> ApiBean<T> failed(T data) {
        return result(data, StateCode.FAILED);
    }

    public static <T> ApiBean<String> success() {
        return success("success");
    }

    public static <T> ApiBean<T> success(T data) {
        return result(data, StateCode.SUCCESS);
    }

    public static <T> ApiBean<?> successPage(IPage<T> page) {
        Map<String, Object> data = new HashMap<>();
        data.put("list", page.getRecords());
        data.put("pages", page.getPages());
        data.put("total", page.getTotal());
        data.put("size", page.getSize());
        data.put("offset", page.offset());
        return result(data, StateCode.SUCCESS);
    }

    public static ApiBean<Object> result(StateCode stateCode) {
        return result(null, stateCode);
    }

    public static <T> ApiBean<T> result(T data, StateCode stateCode) {
        return new ApiBean<T>(data, stateCode.getCode(), stateCode.getMsg());
    }
}
